package com.kaifamiao.trace;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

@WebServlet( "/cookie/counter" )
public class CookieCounterServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        int counter = 0 ;
        // 尝试从 请求头 中获取 cookie
        Cookie[] cookies = request.getCookies();
        if( cookies != null && cookies.length > 0 ){
            for( int i = 0 ; i < cookies.length ; i++ ){
                Cookie ck = cookies[ i ];
                String name = ck.getName() ; // 获得 cookie 的名称
                if( "counter".equals( name ) ) {
                    String value = ck.getValue(); // 获取 cookie 的值
                    counter = Integer.parseInt( value ) ; // String 转 int
                    break ;
                }
            }
        }

        counter++ ;

        // 创建Cookie实例
        Cookie cookie = new Cookie( "counter" , String.valueOf( counter ) );
        // 将Cookie添加到 响应头 ( set-cookie )
        response.addCookie( cookie );
        // 设置响应头中 content-type 字段的值
        response.setContentType( "text/html;charset=UTF-8" );
        // 获得可以向 "响应对象" 中输出字符数据的打印流
        PrintWriter out = response.getWriter();
        // 向 "响应对象" 中输出字符数据
        out.println( "<h3 style='text-align:center;'>" );
        out.println( counter );
        out.println( "</h3>" );
    }

}
